;
(function(root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(["util"], factory);
    } else {
        root.legendofkage = root.legendofkage || {};
        root.legendofkage.Listener = factory();
    }
})
(this, function() {

    function Listener() {
        this.evtType = {};
    }
    var p = Listener.prototype;
    //注册事件
    p.on = function(eventName, eventHandler) {
        if (!eventHandler || typeof eventHandler != "function") {
            return;
        }
        var handlers = this.evtType[eventName];
        !Array.isArray(handlers) && (this.evtType[eventName] = handlers = []);
        handlers.push(eventHandler);
    }

    //注册事件(与on不同的是，无论注册同一事件多少次，其事件处理函数只触发最后一次注册的)
    p.once = function(eventName, eventHandler) {
        if (!eventHandler || typeof eventHandler != "function") {
            return;
        }
        this.evtType[eventName] = [eventHandler];
    }

    //触发事件
    p.dispatch = function(eventName, eventParam) {
        var listeners = this.evtType[eventName];
        if (listeners) {
            listeners.forEach(function(item, index) {
                item(eventParam);
            });
        }
    }

    //移除已注册事件(当没有提供fn时，则删除eventName中的所有处理函数)
    p.un = function(eventName, fn) {
        var listeners = this.evtType[eventName];
        if (!listeners)
            return;
        if (fn != null && typeof fn == "function") {
            var index = listeners.indexOf(fn);
            listeners.splice(index, 1);
        } else {
            listeners.length = 0;
        }
        if (listeners.length == 0) {
            delete this.evtType[eventName];
        }
    }

    //移除所有已注册事件
    p.unAll = function() {
        var keys = Object.keys(this.evtType);
        for (var i = 0, j = keys.length; i < j; i++) {
            this.evtType[keys[i]].length = 0;
            delete this.evtType[keys[i]];
        }
    }
    return Listener;
});